import store from '@/store'
import CryptoJS from 'crypto-js'
import axios from 'axios'
import { BASE_URL_REQUEST } from '@/config/index'
import { ElMessage } from 'element-plus'

// 把路径转换成驼峰命名
export const pathToCamel = (path: string): string => {
	return path.replace(/\/(\w)/g, (all, letter) => letter.toUpperCase())
}

// 获取svg图标(id)列表
export const getIconList = (): string[] => {
	const rs: string[] = []
	const list = document.querySelectorAll('svg symbol')
	for (let i = 0; i < list.length; i++) {
		rs.push(list[i].id)
	}
	return rs
}
// 获取图片base64
export const getImageBase64 = (image: any) => {
	const canvas = document.createElement('canvas')
	canvas.width = image.width
	canvas.height = image.height
	const ctx: any = canvas.getContext('2d')
	ctx.drawImage(image, 0, 0, image.width, image.height)
	// 获取图片后缀名
	const extension = image.src
		.substring(image.src.lastIndexOf('.') + 1)
		.toLowerCase()
	// 某些图片 url 可能没有后缀名，默认是 png
	return canvas.toDataURL('image/' + extension, 1)
}
// 将Base64字符串转换成Blob对象
export const dataURLtoBlob = (dataurl: any) => {
    const arr = dataurl.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    
    return new Blob([u8arr], {type: mime});
}
// 下载图片
export const downloadImage = (imageUrl: any, isbase64: boolean = false) => {
	const link = document.createElement('a')
	link.setAttribute('download', '我的邀请码')
	const image = new Image()
	if(isbase64){
		image.src = imageUrl
	}else{
		// 添加时间戳，防止浏览器缓存图片
		image.src = imageUrl + '?timestamp=' + new Date().getTime()
	}
	// 设置 crossOrigin 属性，解决图片跨域报错
	image.setAttribute('crossOrigin', 'Anonymous')
	image.onload = () => {
		if(isbase64){
			link.href = imageUrl
		}else{
			link.href = getImageBase64(image)
		}
		link.click()
	}
}
// 下载文件
export const handleDownload = (url: any,filename: any) => {
	const x = new window.XMLHttpRequest();
	x.open('GET', url, true);
	x.responseType = 'blob';
	x.onload = () => {
		const url = window.URL.createObjectURL(x.response);
		const a = document.createElement('a');
		a.href = url;
		a.download = filename;
		a.click();
	};
	x.send();
}

//加密
export const encrypt = (word: any, keyStr?: any) => {
	keyStr = keyStr ? keyStr : 'zaqxswcde520vfr4';
	let key = CryptoJS.enc.Utf8.parse(keyStr);
	let srcs = CryptoJS.enc.Utf8.parse(word);
	let encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
	return encrypted.toString();
}
//解密
export const decrypt = (word: any, keyStr?: any) => {
	keyStr = keyStr ? keyStr : 'zaqxswcde520vfr4';
	let key = CryptoJS.enc.Utf8.parse(keyStr);
	let decrypt = CryptoJS.AES.decrypt(word, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
	return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}
// 设置router
export const setRouterMenuList = (data: any) => {
	let routerList: any = []
	// 拿到全部菜单类型
	let menuList = data.filter((item: any) => item.type == '1')
	menuList.forEach((item: any) => {
		if (item.module_name == 'top') {
			routerList.push({
				id: item.id,
				name: item.name,
				langcode: item.langcode,
				url: item.route == '/' ? null : item.route,
				openStyle: 0,
				icon: item.icon,
				children: []
			})
		}
	})
	menuList.forEach((item: any) => {
		let itemIndex = routerList.findIndex((f: any) => f.id == item.pid)
		if (itemIndex != -1) {
			routerList[itemIndex].children.push({
				id: item.id,
				name: item.name,
				langcode: item.langcode,
				url: item.route,
				openStyle: 0,
				icon: item.icon,
			})
		}
	})
	// 如果是一级菜单但是没有子菜单的就不显示
	let noneIndex: any = []
	routerList.forEach((item: any,i: any) => {
		if(!item.url && item.children.length == 0){
			noneIndex.push(i)
		}
	});
	noneIndex.forEach((item: any) => {
		routerList.splice(item,1)
	})
	// // .console.log(routerList);
	return routerList
}
// 手动添加mate标签
export const addMeta = (name: any, content: any) => {
	const meta = document.createElement('meta');
	meta.content = content;
	meta.name = name;
	document.getElementsByTagName('head')[0].appendChild(meta);
}

//时间戳转年月日
export const timeResetDate = (value: any = '', nohour: any = false, justhour: any = false, hen: any = '/') => {
	// if (!value) return ''
	// value = value * 1000;
	let time = value ? new Date(value) : new Date();
	let year = time.getFullYear()
	let month: any = time.getMonth() + 1
	let date: any = time.getDate()
	let hours: any = time.getHours()
	let minute: any = time.getMinutes()
	let second: any = time.getSeconds()

	if (month < 10) {
		month = '0' + month
	}
	if (date < 10) {
		date = '0' + date
	}
	if (hours < 10) {
		hours = '0' + hours
	}
	if (minute < 10) {
		minute = '0' + minute
	}
	if (second < 10) {
		second = '0' + second
	}
	if (nohour) {
		return year + hen + month + hen + date
	} else if (justhour) {
		return hours + ':' + minute + ':' + second
	} else {
		return year + hen + month + hen + date + ' ' + hours + ':' + minute + ':' + second
	}
}
// 清除为空''的对象属性
export const clearEmptyProp = (obj: any) => {
	for (let key in obj) {
		if (obj[key] === '' || obj[key] === null) {
			delete obj[key]
		}else if(Array.isArray(obj[key])){
			obj[key].forEach((item: any) => {
				clearEmptyProp(item)
			});
		}
	}
	return obj
}
// 对象属性是否都为空值
export const isEmptyProp = (obj: any) => {
	let isEmpty = true
	for (let key in obj) {
		if(obj[key] != null && obj[key] != ""){
			isEmpty = false
		}
	}
	return isEmpty
}
// 对象数组的值验证（type:1是否全部为空，type2:是否包含空值）
export const isEmptyArray = (arr: any,type: any = 2) => {
	let isEmpty = false
	arr.forEach((item: any) => {
		if(type == 2 && Object.values(item).some((i:any)=>i==='')){
			isEmpty = true
		}
		if(type == 1 && Object.values(item).every((i:any)=>i==='')){
			isEmpty = true
		}
	});
	return isEmpty
}

//获取url参数
export const getUrlParam = (key: any) => {
  const url = location.href
  // 获取 hash 值，不包含 '#' 号
  const hash = url.substring(url.indexOf("#") + 1)
  // 查找 '?' 号所在的索引
  const searchIndex = hash.indexOf("?")
  // '?' 号后面接的是索引参数，如果找到则+1，去除'?' 号
  const search = searchIndex !== -1 ? hash.substring(searchIndex + 1) : ""
  // 把搜索参数字符串提过URLSearchParams转成对象形式
  const usp = new URLSearchParams(search)
  // 通过URLSearchParams自带的get方法，查询键所对应的值
  return usp.get(key)
}

//获取url全部参数（数组形式）
export const getUrlParamAll = () => {
  const url = location.href
  // 获取 hash 值，不包含 '#' 号
  const hash = url.substring(url.indexOf("#") + 1)
  // 查找 '?' 号所在的索引
  const searchIndex = hash.indexOf("?")
  // '?' 号后面接的是索引参数，如果找到则+1，去除'?' 号
  const search = searchIndex !== -1 ? hash.substring(searchIndex + 1) : ""
  // 把搜索参数字符串拆成数组
  const dataList = search ? search.split('&') : []
  // 转换成对象数组
  return dataList.map((i: any) => {
		const obj: any = {}
		obj[i.split('=')[0]] = i.split('=')[1]
		return obj
	})
}

//获取url参数(简易版只有一个参数且在最后)
export const getUrlParamSelp = (key: any) => {
	const url = location.href
	return url.slice(url.indexOf(key+"=")+key.length+1)
  }

//手机号隐秘操作加*
export const phoneToSecret = (phone: any) => {
	let str = String(phone);
	if (str.length != 11) {
		return phone
	} else {
		return str.slice(0, 3) + "****" + str.slice(7);
	}
}

//复制内容到剪贴板
export const copy = (text: any) => {
	return new Promise((resolve,reject) => {
		try {
			if(navigator.clipboard && navigator.clipboard.writeText){
				navigator.clipboard.writeText(text).then(() => {
					resolve(true)
				});
			}else{
				let oInput = document.createElement('input');
				oInput.value = text;
				document.body.appendChild(oInput);
				oInput.select(); // 选择对象
				document.execCommand("Copy"); // 执行浏览器复制命令
				oInput.className = 'oInput';
				oInput.style.display='none';
				resolve(true)
			}
		} catch (error) {
			reject(true)
		}
		
	})
}

// 判断是否有权限
export const hasRule = (rule: any) => {
	return true
	if(!rule){
		return false
	}else{
		return store.routerStore.menuList.some((item: any) => rule.split(",").includes(item.route))
	}
}

/**
 * [getFileType 下载文档对应的类型]
 * @param  {[type]} type [description]
 * @param  {[type]} id   [description]
 * @return {[type]}      [description]
 */
 export function getFileType(id: any) {
	let arr = [
	  { type: "doc", application: "application/msword" },
	  {
		type: "docx",
		application:
		  "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
	  },
	  { type: "dot", application: "application/msword" },
	  {
		type: "dotx",
		application:
		  "application/vnd.openxmlformats-officedocument.wordprocessingml.template"
	  },
	  { type: "xls", application: "application/vnd.ms-excel" },
	  {
		type: "xlsx",
		application:
		  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
	  },
	  { type: "ppt", application: "application/vnd.ms-powerpoint" },
	  {
		type: "pptx",
		application:
		  "application/vnd.openxmlformats-officedocument.presentationml.presentation"
	  },
	  { type: "pdf", application: "application/pdf" },
	  { type: "txt", application: "text/plain" },
	  { type: "gif", application: "image/gif" },
	  { type: "jpeg", application: "image/jpeg" },
	  { type: "jpg", application: "image/jpeg" },
	  { type: "png", application: "image/png" },
	  { type: "css", application: "text/css" },
	  { type: "html", application: "text/html" },
	  { type: "htm", application: "text/html" },
	  { type: "xsl", application: "text/xml" },
	  { type: "xml", application: "text/xml" },
	  { type: "mpeg", application: "video/mpeg" },
	  { type: "mpg", application: "video/mpeg" },
	  { type: "avi", application: "video/x-msvideo" },
	  { type: "movie", application: "video/x-sgi-movie" },
	  { type: "bin", application: "application/octet-stream" },
	  { type: "exe", application: "application/octet-stream" },
	  { type: "so", application: "application/octet-stream" },
	  { type: "dll", application: "application/octet-stream" },
	  { type: "ai", application: "application/postscript" },
	  { type: "dir", application: "application/x-director" },
	  { type: "js", application: "application/x-javascript" },
	  { type: "swf", application: "application/x-shockwave-flash" },
	  { type: "xhtml", application: "application/xhtml+xml" },
	  { type: "xht", application: "application/xhtml+xml" },
	  { type: "zip", application: "application/zip" },
	  { type: "mid", application: "audio/midi" },
	  { type: "midi", application: "audio/midi" },
	  { type: "mp3", application: "audio/mpeg" },
	  { type: "rm", application: "audio/x-pn-realaudio" },
	  { type: "rpm", application: "audio/x-pn-realaudio-plugin" },
	  { type: "wav", application: "audio/x-wav" },
	  { type: "bmp", application: "image/bmp" }
	];
	return findArrayReturnValue(arr, "type", id, "application");
  }
  
/**
 * @param arr 查找数组
 * @param property 查找属性
 * @param value 查找值
 * @des:查找到值后返回其值
 */
 export const findArrayReturnValue = (arr: any, property: any, value: any, findKey: any) => {
	let len, findValue;
	if (!Array.isArray(arr)) {
	  return;
	}
	len = arr.length;
	for (var i = 0; i < len; i++) {
	  if (
		arr[i].hasOwnProperty(property) &&
		arr[i][property] == value &&
		arr[i].hasOwnProperty(findKey)
	  ) {
		findValue = arr[i][findKey];
		break;
	  }
	}
	return findValue;
  };
  
/** download All*/
export const downMethod = (data: any) => {
	return new Promise((resolve) => {
		const userStore = store.userStore
		axios({
			method: data.method,
			url: BASE_URL_REQUEST + data.url,
			params: clearEmptyProp(data.params),
			headers:{
				'Authorization':userStore.token
			},
			responseType: "blob"
		  }).then(res => {
			const link = document.createElement("a");
			let blob = new Blob([res.data], {
			  type: getFileType(data.fileType)
			});
			link.style.display = "none";
			link.href = URL.createObjectURL(blob);
			link.download = data.fileName //下载的文件名
			document.body.appendChild(link);
			link.click();
			document.body.removeChild(link);
			resolve(true)
		  }).catch(() => {
			resolve(false)
		  })
	})
};
/** download All*/
export const downMethodOss = (data: any) => {
	return new Promise((resolve) => {
		const userStore = store.userStore
		axios({
			method: data.method,
			url: data.url,
			params: clearEmptyProp(data.params),
			headers:{
				'Authorization':userStore.token
			},
			responseType: "blob"
		  }).then(res => {
			const link = document.createElement("a");
			let blob = new Blob([res.data], {
			  type: getFileType(data.fileType)
			});
			link.style.display = "none";
			link.href = URL.createObjectURL(blob);
			link.download = data.fileName //下载的文件名
			document.body.appendChild(link);
			link.click();
			document.body.removeChild(link);
			resolve(true)
		  }).catch(() => {
			resolve(false)
		  })
	})
};
/** download All a标签下载 */
export const downNewFileWithUrl = (url, fileName) => {
	const link = document.createElement("a");
	link.style.display = "none";
	link.href = url;
	link.download = fileName //下载的文件名
	document.body.appendChild(link);
	link.click();
	document.body.removeChild(link);
};
  
// 是否微信内打开
export const isWeixin = () => {
	let ua: any = navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		return true;
	} else {
		return false;
	}
}

// 是否QQ内打开
export const isQQ = () => {
	let ua: any = navigator.userAgent.toLowerCase();
	if (ua.match(/QQ/i) == 'qq') {
		return true;
	} else {
		return false;
	}
}

// 字符串截取显示
export const strSlice = (str: any,start: number,end: number) => {
	if(!str){
		return str
	}else{
		return str.slice(start,end)
	}
}

// 计算+-*/
export const setPrice = (num1: any, num2: any, fuhao: any) => {
	if (isNaN(num1) || isNaN(num2)) {
		return 0
	} else {
		if (fuhao == '+') {
			return Number(Number(num1) + Number(num2)).toFixed(2)
		} else if (fuhao == '-') {
			return Number(Number(num1) - Number(num2)).toFixed(2)
		} else if (fuhao == '*') {
			return Number(Number(num1) * Number(num2)).toFixed(2)
		} else if (fuhao == '/') {
			return Number(Number(num1) / Number(num2)).toFixed(2)
		}else{
			return 0
		}
	}
}

// 数字输入框不能输入负数
export const notNoNumber = (obj: any,prop: any,e: any,min: any = 0,max: any = 999999999) => {
	if(Number(e) < Number(min) || isNaN(e)){
		obj[prop] = Number(min)
	}else if(Number(e) > Number(max)){
		obj[prop] = Number(max)
	}
}

// URL里特熟字符处理
export const spaceStrToString = (str: any) => {
	// let spaceList = ['%2B','%20','%2F','%3F','%25','%23','%26','%3D']
	// let spaceAfter = ['+','+','/','?','%','#','&','=']
	// spaceList.forEach((item: any,i: any) => {
	// 	str.replace(/new RegExp(item,"g")/,spaceAfter[i])
	// })
	str = str.replace(/%2B/g,"+")
	str = str.replace(/%20/g,"+")
	str = str.replace(/%2F/g,"/")
	str = str.replace(/%3F/g,"?")
	str = str.replace(/%25/g,"%")
	str = str.replace(/%23/g,"#")
	str = str.replace(/%26/g,"&")
	str = str.replace(/%3D/g,"=")
	return str
}

// 保留几位小数,默认保留两位
export const setNumber = (e: any,i: any = 2) => {
	if(isNaN(e)){
		return e
	}else{
		return Number(e).toFixed(i)
	}
}

// 设置对象属性完善度
export const setPerfect = (obj: any,keyList: any,str: any = '%') => {
	// console.log(Object.keys(obj));
	let point = 0,max = 0;
	for (let index = 0; index < keyList.length; index++) {
		max++
		if ((keyList[index] == 'main_platform_id' || keyList[index] == 'main_type_id') && obj[keyList[index]] != 0) {
			point++
		}else if (keyList[index] != 'main_platform_id' && keyList[index] != 'main_type_id' && obj[keyList[index]] !== '' && obj[keyList[index]] !== null && obj[keyList[index]] !== undefined && obj[keyList[index]]?.length != 0) {
			point++
		}else{
			// console.log(keyList[index]);
		}
	}
	let pointMax = point/max*100
	pointMax = pointMax >= 100 ? 100 : pointMax
	return `${(pointMax).toFixed(0)}${str}`
}

// 判断是否为JSON字符串
export const isJSONTest = (str: any) => {
	if(typeof str != 'string'){
		return false
	}else{
		try {
			let ooobj = JSON.parse(str)
			return true
		} catch (e) {
			return false
		}
	}
}

// 菜单权限过滤规则
export const filterMenu = (data: any) => {
	if(Array.isArray(data)){
		return data.filter((i:any)=>i.name!='店铺资料模板分组管理')
	}else{
		return data
	}
}

// JS生成随机数:len生成位数
export const randomNumber = (len: any = 1) => {
	let numList = ['0','1','2','3','4','5','6','7','8','9']
	let returnNum = ''
	for (let index = 0; index < len; index++) {
		returnNum += numList[Math.floor(Math.random()*10)];
	}
	return returnNum
}

// JS数组去重-一位数组

// 处置早晚班时间显示
export const setTimeStr = (str: any,lit: any = ',',len: any = ' - ') => {
	if(!str){
		return str
	}else{
		return str.split(lit)[0] + len + str.split(lit)[1]
	}
}

// 计算距离时间天小时分
export const dateDuration = (time: any) => {
	let timeRight = time
	if(timeRight.indexOf('-') != -1){
		timeRight = timeRight.replace(/-/g,'/')
	}
	let d1 = new Date(timeRight).getTime()
	let d2 = new Date().getTime()
	if(d2 >= d1){
		return '0天0小时0分'
	}else{
		let cha: any = Math.abs(d1 - d2)
		let days = Math.floor(cha / (24 * 60 * 60 * 1000))
		let hours = Math.floor(cha % (24 * 60 * 60 * 1000) / (60 * 60 * 1000))
		let minst = cha % (60 * 60 * 1000) / (60 * 1000)
		if(minst > 0 && minst < 1){
			minst = 1
		}
		let mins =  Math.floor(minst)
		if (days) {
		  return `${days}天${hours}小时${mins}分`
		} else if (hours) {
		  return `0天${hours}小时${mins}分`
		} else {
		  return `0天0小时${mins}分`
		}
	}
  }

	// 处理后端返回的提示语，cn、en
	export const showMsgByServer = (msgObj: any, type: any = 'success') => {
		const lang = localStorage.getItem('lang')
		let msg = ''
		if (!lang || lang.includes('zh-CN')) {
			msg = msgObj.cn
		} else {
			msg = msgObj.en
		}
		if (type == 'success') {
			ElMessage.success(msg)
		} else if (type == 'error') {
			ElMessage.error(msg)
		} else if (type == 'warning') {
			ElMessage.warning(msg)
		}
	}